package tool

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"
)

//使用该方法时
// 1 需要注意domain 和 dao的字段顺序保持一次 数量保持一致
// 2 类型之间不一致需要添加 con 标签进行转换

func ConvertDTOToDAO(dto, dao interface{}) {
	dtoValue := reflect.ValueOf(dto)
	daoValue := reflect.ValueOf(dao).Elem()
	dtoType := dtoValue.Type()

	for i := 0; i < dtoValue.NumField(); i++ {
		dtoField := dtoValue.Field(i)
		daoField := daoValue.Field(i)
		jsonTag := dtoType.Field(i).Tag.Get("con")
		if strings.Contains(jsonTag, "date") {
			t, ok := dtoField.Interface().(time.Time)
			if ok {
				daoField.SetInt(t.UnixMilli())
			}
		} else if strings.Contains(jsonTag, "parseIntSlice") {
			daoField.SetString(strings.Join(stringifyIntSlice(dtoField.Interface().([]int32)), ","))
		} else {
			daoField.Set(dtoField)
		}
	}
}

func ConvertDAOToDTO(dao, dto interface{}) {
	daoValue := reflect.ValueOf(dao)
	dtoValue := reflect.ValueOf(dto).Elem()
	dtoType := dtoValue.Type()
	for i := 0; i < daoValue.NumField(); i++ {
		daoField := daoValue.Field(i)
		dtoField := dtoValue.Field(i)
		jsonTag := dtoType.Field(i).Tag.Get("con")
		if strings.Contains(jsonTag, "date") {
			if daoField.Type() == reflect.TypeOf(int64(0)) {
				timestamp := daoField.Int()
				//c := time.UnixMilli(timestamp)
				//n := c.Format("2006-01-02 15:04:05")
				//fmt.Println(c.Format("2006-01-02 15:04:05"))
				//dtoField.Set(reflect.ValueOf(n))
				dtoField.Set(reflect.ValueOf(time.UnixMilli(timestamp)))
			}
		} else if strings.Contains(jsonTag, "parseIntSlice") {
			dtoField.Set(reflect.ValueOf(ParseIntSlice(daoField.String(), ",")))
		} else {
			dtoField.Set(daoField)
		}
	}
}

func ParseIntSlice(s, sep string) []int32 {
	strSlice := strings.Split(s, sep)

	var intSlice []int32
	for _, str := range strSlice {
		i, err := strconv.Atoi(str)
		if err == nil {
			intSlice = append(intSlice, int32(i))
		}
	}

	return intSlice
}

func stringifyIntSlice(slice []int32) []string {
	strSlice := make([]string, len(slice))
	for i, val := range slice {
		strSlice[i] = fmt.Sprint(val)
	}
	return strSlice
}
func FormatUnixTime(unixTime int64) string {
	if unixTime > 0 {
		timeObj := time.UnixMilli(unixTime)
		return timeObj.Format("2006-01-02 15:04:05")
	}
	return "未知时间"
}
